package dao

import (
	"github.com/jinzhu/gorm"
	"pojo/model"
	"pojo/form"
	"bytes"
)

// 新闻需要访问数据库的对象
type NewsDao struct {
	db *gorm.DB
}

// 构造NewsDao需要传入数据库的对象
func NewNewsDao(db *gorm.DB) *NewsDao {
	return &NewsDao{
		db: db,
	}
}

// 添加新闻信息
func (this *NewsDao) InsertNews(news *model.News) (error) {
	// 把新闻信息插入数据库 返回一个信息
	result := this.db.Save(&news)

	return result.Error
}

// 查询新闻信息
func (this *NewsDao) List(query *form.NewsPageQueryForm) ([]*model.News, error) {

	news := make([] *model.News, 0)

	offset := (query.Page - 1) * query.Limit

	params := make([]interface{}, 0)

	buf := new(bytes.Buffer)
	buf.WriteString(" 1 = 1 ")

	if len(query.Title) > 0 {
		buf.WriteString(" and title like ? ")
		params = append(params, query.Title)
	}

	rs := this.db.Where(buf.String(), params...).Order("created_at").Offset(offset).Limit(query.Limit).Find(&news)

	return news, rs.Error
}

// 统计新闻条数
func (this *NewsDao) Count(query *form.NewsPageQueryForm) (uint64, error) {

	var total uint64

	params := make([]interface{}, 0)

	buf := new(bytes.Buffer)
	buf.WriteString(" 1 = 1 ")

	if len(query.Title) > 0 {
		buf.WriteString(" and title like ? ")
		params = append(params, query.Title+"%")
	}

	rs := this.db.Model(model.News{}).Where(buf.String(), params...).Count(&total)

	return total, rs.Error
}

// 根据ID查询新闻
func (this *NewsDao) FindNews(id uint64) (*model.News, error) {

	news := &model.News{}

	result := this.db.Where("id = ?", id).Find(news)

	return news, result.Error
}

// 根据id 修改对应的 新闻
func (this *NewsDao) UpdateNews(news *form.NewsForm) (error) {

	result := this.db.Model(model.News{}).Where("id = ?", news.Id).Updates(map[string]interface{}{
		"title":   news.Title,
		"content": news.Content,
		"img":     news.Img,
	})

	return result.Error
}

// 删除 新闻
func (this *NewsDao) DeleteNews(id uint64) (error) {
	result := this.db.Where("id = ?", id).Delete(&model.News{})
	return result.Error
}
